#!/usr/bin/env python
#-*-coding:utf-8-*-

import sqlite3 as sl
import sys, os, time

class CykloryDB():
  def __init__(self):
    self.con = None
    try:
      self.con = sl.connect(os.environ["HOME"]+"/.cyklory/cyklory2.db")
      self.cur = self.con.cursor()
      table_list = [
       'Subjects(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)',
       'Curriculums(id INTEGER PRIMARY KEY AUTOINCREMENT, subject_id INTEGER, name TEXT, data TEXT)',
       'Tests(id INTEGER PRIMARY KEY AUTOINCREMENT, subject_id INTEGER, curriculum_id INTEGER, name TEXT)',
       'Testdatas(id INTEGER PRIMARY KEY AUTOINCREMENT, subject_id INTEGER, test_id INTEGER, description TEXT, choices TEXT, solution TEXT)'
#  Szótárak is kellenek!
      ]
      map(self.cur.execute, map(lambda t: "CREATE TABLE IF NOT EXISTS "+t, table_list))
      self.con.commit()

    except sl.Error, e:
      print "Error %s:" % e.args[0]
      sys.exit(1)
      
  def get(self, cols, table, w=None, t=True):
    wh = ""
    if type(w) == dict:
      wh = " WHERE "+",".join(map(lambda e: e+"='"+str(w[e])+"'", w))
    self.cur.execute("SELECT " + cols + " FROM " + table + wh)
    if t:
      return self.cur.fetchall()     
    else:
      return self.cur.fetchone()[0]
      
  def set(self, table, id, args):
    command = "UPDATE "+table+" SET "+",".join(map(lambda e: e+"='"+args[e]+"'", args)) + " WHERE id="+id
    self.cur.execute(command)
    self.con.commit()
  
  def new(self, table, values, id='null'):
    if type(values) == list:
      command = "INSERT INTO "+table+" VALUES ("+id+","+",".join(map(lambda e: "'"+e+"'", values))+")"
    else:
      command = "INSERT INTO "+table+" VALUES ("+id+",'"+values+"')"
    self.cur.execute(command)
    self.con.commit()
    
  def get_subjects(self):
    return self.get("*", "Subjects")
    
  def get_curriculums(self, subject):
    return self.get("id, name", "Curriculums", {"subject_id":subject})

  def get_curdata(self, curriculum):
    d = self.get("data", "Curriculums", {"id":curriculum}, False)
    return d
    
  def get_tests(self, subject):
    pass
    
  def get_testdata(self, subject, test):
    pass
   
  def edit_curriculum(self, subject, curriculum_name, curdata):
    pass
    
  def edit_test(self, subject, test_name, testdata):
    pass
    
  def rm_subject(self, subject):
    pass
    
  def rm_curriculum(self, subject, curriculum):
    pass
    
  def rm_test(self, subject, test):
    pass

